package com.greatpengcode.controller;

import com.greatpengcode.pojo.User;
import com.greatpengcode.service.impl.LoginServiceImpl;
import com.greatpengcode.utils.MD5Util;
import com.greatpengcode.utils.Sha1Util;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.ui.Model;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestParam;
import org.thymeleaf.util.StringUtils;

import javax.servlet.http.HttpSession;
import java.security.NoSuchAlgorithmException;

@Controller
public class LoginController {
    @Autowired
    private LoginServiceImpl loginService;
    @PostMapping("/user/login")
    public String login(@RequestParam("username") String username, @RequestParam("password") String password, Model model, HttpSession session) throws NoSuchAlgorithmException {
        if (!StringUtils.isEmpty(username)){
            User user = loginService.getUserByName(username);
            if (user!=null && user.getPassword().equals(MD5Util.getMD5String(password))){
                session.setAttribute("loginUser",username);
                return "redirect:/main.html";
            }
            else{
                model.addAttribute("msg","用户名或密码错误");
                return "index";
            }
        }
        else{
            model.addAttribute("msg","用户名为空");
            return "index";
        }
    }

    @RequestMapping("/user/logout")
    public String logout(HttpSession session){
        session.invalidate();
        return "redirect:/index.html";
    }

    @GetMapping("/user/addUser")
    public String toAddRegisterPage(){
        return "redirect:/register.html";
    }

    @PostMapping("/user/addUser")
    public String addUser(User user) throws NoSuchAlgorithmException {
        user.setPassword(MD5Util.getMD5String(user.getPassword()));
        loginService.addUser(user);
        return "redirect:/index.html";
    }
}
